<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px"
     >
      <el-form-item :label="$t('service_order_type_name')" prop="serviceOrderName">
        <el-input @keyup.enter.native="handleQuery" v-model="queryParams.serviceOrderName" :placeholder="$t('please_enter', { name: $t('service_order_type_name') })
          " clearable />
      </el-form-item>
      <el-form-item :label="$t('submitted_by')" prop="createBy">
        <el-input @keyup.enter.native="handleQuery" v-model="queryParams.createBy" :placeholder="$t('please_enter', { name: $t('submitted_by') })
          " clearable />
      </el-form-item>
      <el-form-item :label="$t('select_priority')" prop="priority">
        <el-select
          v-model="queryParams.priority"
          :placeholder="$t('please_select', { name: $t('select_priority') })"
          clearable
        >
          <el-option
            v-for="dict in dict.type.service_order_priority"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('Service_order_label')" prop="label">
        <el-input @keyup.enter.native="handleQuery" v-model="queryParams.label" :placeholder="$t('please_enter', { name: $t('Service_order_label') })
          " clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("search") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
          $t("reset")
        }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
      <el-col :span="22">
        <el-tabs v-model="queryParams.status" @tab-click="handleQuery">
          <template v-for="dict in dict.type.service_list_status">
            <el-tab-pane :label="dict.label" :name="dict.value" :key="dict.label"></el-tab-pane>
          </template>
        </el-tabs>
      </el-col>
      <el-col :span="1.5" v-if="$route.query.type == 0">
        <el-button type="primary" plain icon="el-icon-plus" size="mini"
          v-hasPermi="['serviceUnit:serviceUnitListSend:add']" @click="handleAdd">{{ $t("add_new_service_order")
          }}</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="listList" @selection-change="handleSelectionChange" border :max-height="tableHeight">
      <el-table-column :label="$t('service_order_type')" align="center" prop="serviceOrderName"
        :show-overflow-tooltip="true"></el-table-column>
      <el-table-column :label="$t('service_order_number')" align="center" prop="serviceOrderCode"
        :show-overflow-tooltip="true"></el-table-column>
      <el-table-column :label="$t('submitted_by')" align="center" prop="createBy" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('employing_company')" align="center" prop="employerName"
        :show-overflow-tooltip="true" />
      <el-table-column :label="$t('select_priority')" align="center" prop="createBy" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.priority == '2' ? 'red' : '' }"><dict-tag
              :options="dict.type.service_order_priority" :value="scope.row.priority" /></span>

        </template>
      </el-table-column>
      <el-table-column :label="$t('Service_order_label')" align="center" prop="label" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('content')" align="center" prop="remark" :show-overflow-tooltip="true">
        <template slot-scope="scope">
           <div v-html="scope.row.remark"></div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('contact_person')" align="center" prop="dockingPersonName"
        :show-overflow-tooltip="true" />
      <el-table-column :label="$t('status')" align="center" prop="status" v-if="$route.query.type == 1">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.service_list_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('action')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)" v-hasPermi="[
            'serviceUnit:serviceUnitListReceive:view',
            'serviceUnit:serviceUnitListSend:view',
          ]">{{ $t("view") }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-link" @click="handleEdit(scope.row)" v-hasPermi="[
            'serviceUnit:serviceUnitListReceive:edit',
            'serviceUnit:serviceUnitListSend:edit',
          ]" v-if="scope.row.status == 10">{{ $t("modify") }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-link" @click="handleView(scope.row)" v-hasPermi="[
            'serviceUnit:serviceUnitListReceive:edit',
            'serviceUnit:serviceUnitListSend:edit',
          ]" v-if="$route.query.type == 1 && scope.row.status == 1">{{ $t("handle") }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList"
      :page-sizes="[10,20,30,50,100, 200]"
      />

    <!-- 添加或修改服务单列对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('select_employing_company')">
              <employerSelect :disabled="userData.userType == '02'" v-model="form.employerId" @change="getSelectData">
              </employerSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('select_the_service_order_type')" prop="serviceOrderName">
              <el-select v-model="form.serviceOrderId" @change="chooseOrderCode" :placeholder="$t('service_order_code')"
                clearable filterable>
                <el-option v-for="dict in unitList" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('service_order_code')" prop="serviceOrderCode">
              <el-input v-model="form.serviceOrderCode" disabled style="width:190px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('service_order_type_remarks')" prop="typeRemark">
              <el-input v-model="form.typeRemark" disabled style="width:190px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('select_priority')" prop="priority">
              <el-select v-model="form.priority" :placeholder="$t('select_priority')" clearable filterable>
                <el-option v-for="dict in dict.type.service_order_priority" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('Service_order_title')" prop="serviceOrderTitle">
              <el-input v-model="form.serviceOrderTitle" style="width:190px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item :label="$t('Service_order_label')">
          <div v-for="(domain, index) in form.labels" :key="index" style="margin-bottom:10px">
            <el-input v-model="domain.value" style="width:190px;margin-right:10px"></el-input>
            <el-button @click.prevent="removeDomain(domain)" v-if="index != 0">删除</el-button>
            <el-button @click.prevent="addDomain(domain)" v-if="index == 0">增加</el-button>
          </div>
        </el-form-item>
        <el-form-item :label="$t('service_order_description')" prop="remark">
          <!-- <el-input v-model="form.remark" :placeholder="$t('please_enter', { name: $t('service_order_description') })
            " :show-word-limit="true" type="textarea" :rows="5" /> -->
            <editor v-model="form.remark"  :placeholder="$t('please_enter', { name: $t('service_order_description') })" :min-height="192"/>
        </el-form-item>
        <el-form-item :label="$t('upload_attachment')" prop="annex">
          <file-upload v-model="form.annex" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm(1)">{{
          $t("save_as_draft")
        }}</el-button>
        <el-button type="primary" @click="submitForm(2)">{{
          $t("confirm")
        }}</el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>
    <!-- 查看详情弹框 -->
    <serviceUnitDetail ref="serviceUnitDetail" @refrshList="getList"></serviceUnitDetail>
  </div>
</template>

<script>
import {
  sendListListList,
  receiveListListList,
  getList,
  delList,
  addList,
  updateList,
  getEmployerServiceOrder,
} from "@/api/custom/serviceUnitList";
import { getAllServiceOrder } from "@/api/custom/serviceUnitType";
import { listUser } from "@/api/custom/employerList";
import employerSelect from "@/views/components/custom/employerSelect";
import serviceUnitDetail from "./detail.vue";
export default {
  name: "List",
  dicts: ["service_list_status", "service_order_priority"],
  components: {
    serviceUnitDetail,
    employerSelect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 服务单列表格数据
      listList: [],
      //服务单类型列表
      serviceOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serviceOrderName: null,
        status: "0",
      },
      // 表单参数
      form: {
        labels: [{ value: '' }]
      },
      // 表单校验
      rules: {
        serviceOrderId: [
          {
            required: true,
            message: this.$t("cannot_empty", {
              name: this.$t("service_order_type"),
            }),
            trigger: "blur",
          },
        ],
        remark: [
          {
            required: true,
            message: this.$t("cannot_empty", {
              name: this.$t("service_order_description"),
            }),
            trigger: "blur",
          },
        ],
      },
      unitList: [],
      searchValue: "",
      employerAllList: [],
    };
  },
  computed: {
    userData() {
      return this.$store.state.user.userData;
    },
  },
  created() {
    this.getList();
    this.getEmployerList();
  },
  methods: {
    getEmployerList() {
      listUser({}).then((response) => {
        this.employerAllList = response.data.records;
      });
    },
    //选择服务单
    chooseOrderCode() {
      this.serviceOrderList.forEach(element => {
        if (element.id == this.form.serviceOrderId) {
          this.form.typeRemark = element.remark
          this.form.serviceOrderCode = element.serviceOrderCode
        }
      });
    },
    //移除标签
    removeDomain(item) {
      var index = this.form.labels.indexOf(item)
      if (index !== -1) {
        this.form.labels.splice(index, 1)
      }
    },
    //添加标签
    addDomain() {
      this.form.labels.push({
        value: ''
      });
    },
    /** 查询服务单列列表 */
    getList() {
      this.loading = true;
      if (this.$route.query.type == 1) {
        receiveListListList(this.queryParams).then((response) => {
          this.listList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        });
      } else {
        sendListListList(this.queryParams).then((response) => {
          this.listList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        });
      }
    },
    getSelectData(params,edit) {
      getEmployerServiceOrder({
        employerId: params.value,
      }).then((response) => {
        console.log("🐛 ~ getSelectData ~ response:", response)
        this.serviceOrderList = response.data;
        this.unitList = response.data.map((item) => {
          return {
            label: item.serviceOrderName,
            value: item.id,
          };
        });
        if (edit) {
          this.serviceOrderList.forEach(element => {
            if (element.id == this.form.serviceOrderId) {
              this.form.typeRemark = element.remark
              this.form.serviceOrderCode = element.serviceOrderCode
            }
          });
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        serviceOrderId: null,
        remark: null,
        annex: null,
        labels: [{ value: "" }]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      if (this.userData.userType == "02") {
        let find = this.employerAllList.find((item) => {
          return item.userId == this.userData.userId;
        });
        this.$set(this.form, "employerId", find.id);
        this.getSelectData({ value: find.id });
      }

      this.open = true;
      this.title = this.$t("add");
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      this.reset();
      const id = row.id || this.ids;
      getList(id).then((response) => {
        this.form = response.data;
        this.getSelectData({ value: this.form.employerId },'edit');
        this.$set(this.form, "labels", JSON.parse(this.form.labelJson));
        if (this.userData.userType == "02") {
          let find = this.employerAllList.find((item) => {
            return item.userId == this.userData.userId;
          });
          this.$set(this.form, "employerId", find.id);
          this.getSelectData({ value: find.id });
        }

        this.open = true;
        this.title = this.$t("modify");
      });
    },
    handleView(row) {
      this.$refs.serviceUnitDetail.showModal(row);
    },
    /** 提交按钮 */
    submitForm(e) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.labels) {
            let list = [];
            this.form.labels.forEach(element => {
              list.push(element.value)
            })
            this.form.label = list.join();
            this.form.labelJson = JSON.stringify(this.form.labels)
          }
          //暂存status为10 发送为0
          if (e == 1) {
            this.form.status = 10;
          } else {
            this.form.status = 0;
          }
          if (this.form.id != null) {
            updateList(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("operation_successful"));
              this.open = false;
              this.getList();
            });
          } else {
            // {
            //   unitId：；列表id
            //   remark:'内容'，
            //   picture：文件
            // }
            addList(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("operation_successful"));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(this.$t('delete_data'))
        .then(function () {
          return delList(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("operation_successful"));
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/list/export",
        {
          ...this.queryParams,
        },
        `list_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
